package product

import (
	"context"
	"time"

	"mall/common/globalkey"
	"mall/service/product/model"
	"mall/service/product/rpc/internal/svc"
	"mall/service/product/rpc/types/product"

	"github.com/zeromicro/go-zero/core/logx"
)

type SearchLogLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSearchLogLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchLogLogic {
	return &SearchLogLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SearchLogLogic) SearchLog(in *product.SearchLogReq) (*product.BaseIDResp, error) {
	var searchLogId uint64
	if in.Keyword != nil && in.VisitorId != nil && in.PlatformId != nil && len(*in.Keyword) > 0 && *in.VisitorId > 0 && *in.PlatformId > 0 {
		log := &model.ProductUserSearchLog{
			UserID:     *in.VisitorId,
			PlatformID: uint(*in.PlatformId),
			Keyword:    *in.Keyword,
			Status:     uint8(globalkey.StatusEnabled),
			CreatedAt:  time.Now(),
		}
		err := l.svcCtx.CurrentProduct.InsertSearchLog(l.ctx, nil, log)
		if err != nil {
			logx.Errorw("SearchLog err", logx.Field("detail", err.Error()))
		} else {
			searchLogId = log.SearchLogID
		}
	}

	return &product.BaseIDResp{
		Id: searchLogId,
	}, nil
}
